import Taro from '@tarojs/taro';

const __cache = {};

const getValue = key => {
  if (__cache[key]) {
    return JSON.parse(__cache[key]);
  }
  __cache[key] = Taro.getStorageSync(key);
  if (!__cache[key]) return null;
  return JSON.parse(__cache[key]);
};

const setValue = (key, value) => {
  if (value == null) {
    __cache[key] = null;
    Taro.removeStorageSync(key);
  } else {
    __cache[key] = JSON.stringify(value);
    Taro.setStorageSync(key, __cache[key]);
  }
};

export default {
  clear() {
    for (let k in __cache) {
      delete __cache[k];
    }
    Taro.clearStorageSync();
  },
  remove(key) {
    setValue(key, null);
  },
  set(key, value, timeout = 3600 * 24 * 365) {
    setValue(key, {
      timeout: timeout * 1000 + Date.now(),
      value
    });
  },
  get(key) {
    const value = getValue(key);
    if (value == null) return null;
    if (value.timeout > Date.now()) {
      return value.value;
    }
    return null;
  }
};
